package com.loyi.ams.gateway.hbmis.rest;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.loyi.ams.gateway.hbmis.dao.IDeviceDAO;
import com.loyi.ams.gateway.hbmis.dao.IHourDataDAO;
import com.loyi.cloud.hbmis.api.IDeviceService;
import com.loyi.cloud.hbmis.api.IHourDataService;
import com.loyi.cloud.hbmis.domain.Device;
import com.loyi.cloud.hbmis.domain.HourData;
import com.netflix.discovery.converters.Auto;

@RestController
@RequestMapping("hourdata")
public class HourDataService implements IHourDataService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private IHourDataDAO hourDAO;

	@Autowired
	private IDeviceService deviceService;

	@Override
	@RequestMapping(value = "findAll", method = RequestMethod.GET)
	public List<HourData> findAll(@RequestParam(value = "starttime", required = true) long starttime,
			@RequestParam(value = "endtime", required = true) long endtime,
			@RequestParam(value = "ptid", required = false) List<String> ptid,
			@RequestParam(value = "pollcode", required = false) List<String> pollcode) {
		return hourDAO.findAll(starttime, endtime, ptid, pollcode);
	}

	/**
	 * 保存小时数据
	 * 
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public void save(@RequestBody HourData data) {
		logger.debug("小时数据" + data);
		long starttime, endtime;
		double value;
		HourData newData;
		Map<String, Object> values;
		List<Device> devices;
		
		long s;
		
		s = System.currentTimeMillis();

		// 通过设备编号查找监测点编号
		devices = deviceService.find(null, data.getDeviceid(), null, Arrays.asList(2));
		// devices.
		if (devices == null || devices.size() == 0) {
			logger.warn(String.format("无法找到对应监测点位,设备编号：%s", data.getDeviceid()));
			return;
		}
		data.setPtid(devices.get(0).getPtid());

		HourData exitData = hourDAO.find(data.getDatatime(), data.getPtid(), data.getPollcode());
		if (exitData == null) {
			// 如果不存在
			hourDAO.insert(data);
		} else {
			data.setDatahourid(exitData.getDatahourid());
			hourDAO.update(data);
		}

		// 如果是臭氧，则计算8小时均值
		if ("4471".equals(data.getPollcode())) {
			endtime = data.getDatatime();
			starttime = DateUtils.addHours(new Date(endtime), -7).getTime();
			
			values = hourDAO.avg(starttime, endtime, Arrays.asList(data.getPtid()), data.getPollcode());
			//logger.info(String.format("计算臭氧8小时,数量=%s", values==null?0:values.get("count")));
			if (values != null && Long.parseLong(values.get("count").toString()) >= 6) {
				
				newData = new HourData();
				newData.setPtid(data.getPtid());
				newData.setChannelid(data.getChannelid());
				newData.setDatatime(data.getDatatime());
				newData.setDeviceid(data.getDeviceid());
				newData.setProtocol(data.getProtocol());
				newData.setUploadtime(new Date().getTime());
				newData.setPollcode("4D71");
				value = Double.parseDouble(values.get("avg").toString());
				newData.setValue(value);
				newData.setMaxValue(value);
				newData.setMinValue(value);
				this.save(newData);
			}
			else{
				logger.warn("臭氧8小时数据缺失，将忽略");
			}

		}
		
		logger.info(String.format("小时数据保存完毕，用时%sms", System.currentTimeMillis() - s));

	}
}
